package com.zhuang.chapter16.work02;

import java.util.ArrayList;
import java.util.Collections;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ThreadMain {
	public static void main(String[] args) {

		ArrayList<String> list = new ArrayList<String>();
		list.add("苹果");
		list.add("手机");
		list.add("华为手机");
		list.add("三洋踏板摩托");
		list.add("迪拜7日游");
		list.add("苹果笔记本");
		list.add("联想笔记本");
		list.add("小米空气净化器");
		list.add("格力空调");
		list.add("海尔冰箱");
		list.add("海信电视");
		// 创建锁对象
		Lock lock = new ReentrantLock();
		// 创建线程A,开启线程
		new Thread(new Runnable() {

			@Override
			public void run() {
				while (!list.isEmpty()) {
					Collections.shuffle(list);
					String award = list.get(0);
					list.remove(award);
					System.out.println("第一组...抽出了一个：" + award);
					lock.lock();
					// 线程A和线程B交换执行关键所在
					try {
						Thread.sleep(2000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					} finally {
						lock.unlock();
					}
				}
			}
		}, "A").start();

		// 创建线程B
		new Thread(new Runnable() {

			@Override
			public void run() {
				while (!list.isEmpty()) {
					Collections.shuffle(list);
					String award = list.get(0);
					list.remove(award);
					System.out.println("第二组...抽出了一个：" + award);
					lock.lock();
					// 线程A和线程B交换执行关键所在
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					} finally {
						lock.unlock();
					}
				}
			}
		}, "B").start();
	}
}
